<script setup lang="ts">
import { ref, onMounted, watch, nextTick, onBeforeUnmount } from 'vue'
import MessageList from '../components/MessageLogList.vue'
import ChatInput from '../components/sendMessage2.vue'
import { ElMessage } from 'element-plus'
import sysCofig from '../config/index.js'
import message from '@/api/message.js'
import tool from '@/util/root'

// defineProps<{ msg: string }>()
const apiUrl = new URL(import.meta.env.VITE_APP_API_URL)
const ipAndPort = `${apiUrl.hostname}:${apiUrl.port}`
const imInput = ref('')
const messages = ref([{}])
const ws = ref()
const messagesScrollBootm =ref(false)
const messageSendStatus = ref(false)
const connectionStatus = ref('断开')
const isHovered = ref()
const scrollContainer = ref(null);
const reconnectTimeout = ref(null); // 重连超时控制
//滚动顶部数据加载状态
const loading = ref(false);
const noMoreData = ref(false);
watch(messagesScrollBootm, () => {
    scrollBootm()
}, { deep: true })
const messageList = ref([])
// const clientId = ref("12322")
const logList = [
    {
        id: 1,
        text: '记录',
        icon: 'edit',
        cssName: "'xuanzho-backgroun'"
    },
    {
        id: 2,
        text: '记录2',
        icon: 'clock',
        cssName: "'xuanzho-backgroun'"
    }
]

onMounted(() => {
    messages.value = []
    connectWebSocket()
})
onBeforeUnmount(() => {
    messageSendStatus.value = false
    if (ws.value) {
        ws.value.close(); // 组件销毁时关闭 WebSocket 连接
    }
})
const logMessageListHeadle = async (data) => {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    console.log(data.data);
    const dataList = data.data;
    if (dataList.records.length <= 0) {
        noMoreData.value = true;
    }
    loading.value = false;
    if(dataList.current >= dataList.pages){
        noMoreData.value = true
    }

    dataList.records.forEach(item => {
        const receivedMessage = {
            type: item.type,
            message: item.content,
            timestamp: new Date(item.createTime).toLocaleString()
        }
        if (item.messageId == sendMessageContent.value.messageId) {
            messages.value.unshift(receivedMessage)
        }
    })
    if (sendMessageContent.value.page === 1) {
        scrollBootm()
    }
}
const connectWebSocket = () => {
    const tokenInfo = tool.data.get("tokenInfo")

    const wsUrl = `ws://${ipAndPort}/im/websocket/info/${localStorage.getItem(sysCofig.TOKEN_NAME)}/${tokenInfo.loginId}`
    // const wsUrl = `ws://${ipAndPort}/ws-connect?clientId=${clientId.value}`
    //   const wsUrl = `${sysConfig.WEBSOCKET_URL}/ws-connect?clientId=${clientId.value}`
    console.log('WebSocket连接地址:', wsUrl)
    ws.value = new WebSocket(wsUrl)
    ws.value.onmessage = (event) => {
        const data = JSON.parse(event.data)
        if (data.code === '3') {
            data.data.forEach(item => {
                messageList.value.push(item)
            })
        } else if (data.code === '5') {
            messageList.value.unshift(data.data)
            sendMessageContent.value.messageId = data.data.messageId
        } else if (data.code === '4') {
            // const dataIndex = JSON.parse(data.data)
            logMessageListHeadle(data)
        } else if (data.code === '2') {
            const receivedMessage = {
                type: 2,
                message: data.data.message,
                timestamp: new Date().toLocaleString()
            }
            if (data.data.messageId == sendMessageContent.value.messageId) {
                messages.value.push(receivedMessage)
            }
            messageSendStatus.value = false
            messagesScrollBootm.value = !messagesScrollBootm.value
        } else if (data.code === '10') {
            messageSendStatus.value = false
            tool.out.outLogin()
        } else {
            ElMessage({
                showClose: true,
                message: data.msg,
                type: 'error',
            })
            messageSendStatus.value = false
        }
    }
    ws.value.onopen = () => {
        connectionStatus.value = '连接'
        console.log('WebSocket打开连接')
        messageList.value = []
        handleReconnect()
    }
    ws.value.onclose = () => {
        connectionStatus.value = '断开'
        console.log('WebSocket关闭连接')
        // route.push('/login')
        handleReconnect()
    }
    ws.value.onerror = (error: object) => {
        connectionStatus.value = 'Error'
        console.error('WebSocket error:', error)
    }
}
// 处理 WebSocket 连接断开后的重连
const handleReconnect = () => {
    console.log(connectionStatus.value);

    // 如果已经在重连，避免重复重连
    if (connectionStatus.value === '连接') {
        return;
    }
    setTimeout(() => {
        console.log("正在尝试重新连接 WebSocket...");
        connectWebSocket();
        reconnectTimeout.value = null; // 重连后清除重连超时
    }, 5000); // 5 秒后重连
};

const sendMessage = (message) => {
    if (ws.value && ws.value.readyState === WebSocket.OPEN) {
        console.log("输入内容:", message)
        messageSendStatus.value = true;
        sendMessageContent.value.sendEnum = 'SEND_MESSAGE_TYPE'
        sendMessageContent.value.message = message
        const send = JSON.stringify(sendMessageContent.value)
        ws.value.send(send)
        const receivedMessage = {
            type: 1,
            message: message,
            timestamp: new Date().toLocaleString()
        }
        messages.value.push(receivedMessage)
        imInput.value = ''
        messagesScrollBootm.value = !messagesScrollBootm.value
    } else {
        console.error('WebSocket 连接未打开')
    }
}
const scrollBootm = () => {
    nextTick(() => {
        if (scrollContainer.value) {
           scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
        }
    });
}
const sendMessageContent = ref({
    sendEnum: '',
    message: '',
    messageId: '',
    size: 10,
    page: 1
})
const addMessage = () => {
    messages.value = []
    sendMessageContent.value = {
        sendEnum: '',
        message: '',
        messageId: '',
        size: 10,
        page: 1
    }
}
const handleMouseOver = (id) => {
    isHovered.value = id
}
const handleMouseLeave = () => {
    isHovered.value = null
}
const dealMessage = (data) => {
    return data === 1 ? '客户端' : '服务端'
}
const handleMessageClick = (id) => {
    sendMessageContent.value.messageId = id;
    sendMessageContent.value.sendEnum = 'OPEN_MESSAGE_TYPE';
    sendMessageContent.value.page = 1;
    sendMessageContent.value.size = 10;
    const send = JSON.stringify(sendMessageContent.value)
    messages.value = []
    ws.value.send(send)
    loading.value = false;
    noMoreData.value = false;
}
const deleteMessageClick = (id) => {
    message.deleteById(id).then(re => {
        messageList.value = messageList.value.filter(item => item.messageId !== id);
    });
}
// 滚动事件处理
const handleScroll = (e) => {
    const container = e.target;
    // 当滚动到顶部且不在加载中且还有更多数据时
    if (messages.value.length >0 && container.scrollTop === 0 && !loading.value && !noMoreData.value) {
        loadMoreMessages();
    }
};

// 加载更多消息
const loadMoreMessages = async () => {
    if (loading.value || noMoreData.value) return;

    loading.value = true;
    // 模拟API调用
    sendMessageContent.value.sendEnum = 'OPEN_MESSAGE_TYPE';
    sendMessageContent.value.page = sendMessageContent.value.page + 1;
    sendMessageContent.value.size = 10;
    const send = JSON.stringify(sendMessageContent.value)
    ws.value.send(send)
};
</script>

<template>
    <div class="flex-row" style="height: 100%;">
        <div class="  left-log  border-radius-free-left background ">
            <div class="flex-column  log-margin">
                <div style="display: flex; align-items: center;">
                    <!-- <img style="border-radius: 50%;" src="../ico/logo.png" height="50px" width="50px" /> -->
                    <span class="logo-text">DeepSeekR1</span>
                </div>
                <div class="add-message kuang-co z-border-background" @click="addMessage()"><el-icon>
                        <Plus />
                    </el-icon><span>新建对话</span></div>
                <div v-for="log in logList" :key="log.id" class="log-item"
                    :class="{ 'active': isHovered === log.id, 'kuang-co': true }" @mouseover="handleMouseOver(log.id)"
                    @mouseleave="handleMouseLeave">
                    <el-icon>
                        <component :is="log.icon"></component>
                    </el-icon>
                    <span style="margin-left: 10px;">{{ log.text }}</span>
                </div>
                <MessageList :messageList='messageList' :messageSendStatus="messageSendStatus"
                    :messageId="sendMessageContent.messageId" @delete="deleteMessageClick" @send="handleMessageClick"
                    style="margin-top: 10px;"></MessageList>
            </div>
        </div>
        <div class="right-text border-radius-free-right">
            <div class="message-text" ref="scrollContainer" @scroll="handleScroll">
                <div v-if="!loading && !noMoreData && messages.length > 0" class="loading-message">加载更多...</div>
                <div v-if="loading" class="loading-message">加载中...</div>
                <div v-if="noMoreData" class="no-more-message">没有更多历史消息了</div>
                <div v-for="(msg, index) in messages" :key="index" style="padding-top: 20px;">
                    <!-- <el-descriptions-item :label="dealMessage(msg.type)" label-align="right">
                        {{ msg.message }}
                    </el-descriptions-item> -->
                    <div :class="msg.type == 1 ? 'right-text-message' : 'left-text-message'">
                        <div v-if="msg.type == 1" class="flex-row-reverse message-container">
                            <div><el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
                            </div>
                            <div class="flex-column message-content ">
                                <div style="margin-bottom: 10px; margin-right: 16px;">{{ msg.timestamp }}</div>
                                <div v-html="msg.message" class="background-message-right message-text-right-css"></div>
                            </div>
                        </div>
                        <div v-else-if="msg.type !== 1" class="flex-row message-container">
                            <div style="white-space: nowrap;">{{ dealMessage(msg.type) }}:</div>
                            <div class="flex-column message-content ">
                                <div style="margin-bottom: 10px; margin-left: 16px;">{{ msg.timestamp }}</div>
                                <div v-html="msg.message" class="background-message-left message-text-left-css"></div>
                            </div>
                        </div>

                    </div>
                </div>
                <span v-if="messageSendStatus" class="waiting-message">等待回答中........</span>
            </div>
            <div class="send-booton">
                <!-- 聊天输入框组件 -->
                <ChatInput :disabled="messageSendStatus" :sending="messageSendStatus" @send="sendMessage" />
            </div>
        </div>
    </div>

</template>

<style scoped>
.loading-message,
.no-more-message {
    text-align: center;
    padding: 10px;
    color: #999;
    font-size: 14px;
}

.waiting-message {
    display: block;
    text-align: center;
    color: #9e9e9e;
    font-size: 14px;
    margin-top: 16px;
}

.left-text-message {
    float: left;
}

.log-margin {
    margin: 15px;
}

.right-text-message {
    float: right;
    margin-right: auto;
}

.z-border-background {
    background-color: #d5cff3;
}

.message-container {
    display: flex;
    align-items: flex-start;
    /* 确保元素顶部对齐 */
    gap: 8px;
    /* 可选：添加一些间距 */
}

.message-content {
    min-width: 10%;
    max-width: 80%;
    /* 限制消息宽度，避免过宽 */
}

.kuang-co {
    /* width: 150px; */
    padding: 5px 15px;
    border-radius: 12px;
    transition: all 0.3s ease;
}

.kuang-log {
    width: 150px;
    padding: 5px 15px;
    border-radius: 5px;
    transition: all 0.3s ease;
}

.logo-text {
    margin-left: 10px;
    margin-right: 10px;
    font-family: 'Arial', sans-serif;
    font-size: 20px;
    font-weight: bold;
    color: #8063b9;
    text-shadow: 2px 2px 4px rgba(46, 80, 235, 0.2);
    letter-spacing: 2px;
}

.add-message {
    border-style: solid;
    border-color: #8063b9;
    border-width: 1px;
    margin-top: 10px;
}

.xuanzho-background {
    background-color: #c9c6c6;
}

.left-log {
    width: 200px;
    /* height: 100%; */
    /* border-style: solid; */
    /* border-color: #876db8; */
    /* border-width: 1px; */
    /* margin-right: 10px; */
}

.background {
    /* background-color: var(--agent-header-model-tab-color, #dddffa); */
    background: linear-gradient(to right, #f5f6ff, #dddffa)
}

.background-message-right {
    background: linear-gradient(to left, #f5f6ff, #dddffa, #dddffa)
}

.background-message-left {
    background: linear-gradient(to right, #f5f6ff, #dddffa, #dddffa)
}

.message-text-right-css {
    padding: 10px 15px;
    border-bottom-left-radius: 10px;
    border-top-left-radius: 10px;
    border-bottom-right-radius: 20px;
    border-top-right-radius: 1px;
    margin-right: 16px;
    text-align: justify;
}

.message-text-left-css {
    width: 80%;
    padding: 10px 15px;
    border-bottom-left-radius: 20px;
    border-top-left-radius: 1px;
    border-bottom-right-radius: 10px;
    border-top-right-radius: 10px;
    margin-left: 16px;
    text-align: justify;
}

.right-text {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    background: linear-gradient(to left, #f5f6ff, #f5f6ff, #f1f1fc)
}

.flex-column {
    display: flex;
    flex-direction: column;
}

.flex-row {
    display: flex;
    flex-direction: row;
}

.flex-row-reverse {
    display: flex;
    flex-direction: row-reverse;
    flex-wrap: wrap;
}

.message-text {
    height: 100%;
    min-height: 10px;
    /* width: 100%; */
    overflow-y: auto;
    display: flex;
    flex-flow: column nowrap;
    padding-left: 18px;
    margin-bottom: 10px;
}

/* Webkit 浏览器自定义滚动条 */
.message-text::-webkit-scrollbar {
    width: 8px;
    height: 1px;
}

.message-text::-webkit-scrollbar-track {
    background: #f0f0f0;
    border-radius: 4px;
}

.message-text::-webkit-scrollbar-thumb {
    background-color: #cec9c9;
    border-radius: 4px;
    height: 2px;
    border: 2px solid #f0f0f0;
}

.message-text::-webkit-scrollbar-thumb:hover {
    background-color: #f7f6f6;
}

.send-booton {
    display: flex;
    flex-flow: row wrap;
    justify-content: center;
}

.border-radius-free-right {
    border-bottom-left-radius: 0px;
    border-top-left-radius: 0;
    border-bottom-right-radius: 10px;
    border-top-right-radius: 10px;
}

.border-radius-free-left {
    border-bottom-left-radius: 10px;
    border-top-left-radius: 10px;
    border-bottom-right-radius: 0px;
    border-top-right-radius: 0px;
}

.read-the-docs {
    color: #888;
}

.el-row {
    margin-bottom: 20px;
}

.el-row:last-child {
    margin-bottom: 0;
}

.el-col {
    border-radius: 4px;
}

.grid-content {
    background-color: #888;
    border-radius: 4px;
    min-height: 36px;
}


/* 日志项样式 */
.log-item {
    margin-top: 4px;
    display: flex;
    align-items: center;
    /* cursor: pointer; */
    /* padding: 8px 12px; */
    /* margin-bottom: 4px; */
}

.log-item:hover {
    background-color: #f0f0f0;
}

.log-item.active {
    background-color: #dbdadb;
    /* color: #1890ff; */
    /* font-weight: 500; */
}

/* 响应式调整 */
@media (max-width: 768px) {
    .flex-row {
        flex-direction: column;
    }

    .right-text {
        width: 100%;
        margin-right: 0;
        margin-bottom: 15px;
    }
}
</style>
